package models

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type SensorData struct {
	// Identical primitive.ObjectID `bson:"_id"`
	DeviceInfo string    `bson:"deviceInfo" form:"deviceInfo"`
	FallDown   bool      `bson:"fallDown" form:"fallDown"`
	Timestamp  int64     `bson:"timestamp" form:"timestamp"`
	SeqDataX   []float64 `bson:"seqDataX" form:"seqDataX"`
	SeqDataY   []float64 `bson:"seqDataY" form:"seqDataY"`
	SeqDataZ   []float64 `bson:"seqDataZ" form:"seqDataZ"`
}

func (SensorData) CollectionName() string {
	return "data"
}

func FilterData(
	startTime int64,
	endTime int64,
	deviceInfo string,
	fallDown string,
	limit int64,
	offset int64,
) ([]*SensorData, error) {
	data := make([]*SensorData, 0)
	filter := bson.M{}
	timestamp := bson.M{}
	if startTime != 0 {
		timestamp["$gte"] = startTime
	}
	if endTime != 0 {
		timestamp["$lte"] = endTime
	}
	filter["timestamp"] = timestamp
	if deviceInfo != "" {
		filter["deviceInfo"] = bson.M{
			"$eq": deviceInfo,
		}
	}
	if fallDown != "" {
		fallDownBool := false
		if fallDown == "true" {
			fallDownBool = true
		}
		filter["fallDown"] = bson.M{
			"$eq": fallDownBool,
		}
	}

	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"timestamp", -1}})
	findOptions.SetSkip(offset)
	if limit > 50 {
		limit = 50 //限制用户单次最大只能请求50条数据
	}
	findOptions.SetLimit(limit)
	cursor, err := Mongo.Collection(
		SensorData{}.CollectionName()).Find(context.Background(),
		filter,
		findOptions,
	)
	if err != nil {
		return nil, err
	}
	for cursor.Next(context.Background()) {
		sd := new(SensorData)
		err = cursor.Decode(sd)
		if err != nil {
			return nil, err
		}
		data = append(data, sd)
	}
	return data, nil

}

func InsertOneSensorData(sd *SensorData) error {
	_, err := Mongo.Collection(SensorData{}.CollectionName()).InsertOne(context.Background(), sd)
	return err
}

func GetSensorData() ([]*SensorData, error) {
	data := make([]*SensorData, 0)
	cursor, err := Mongo.Collection(SensorData{}.CollectionName()).Find(context.Background(), bson.D{})
	if err != nil {
		return nil, err
	}
	for cursor.Next(context.Background()) {
		sd := new(SensorData)
		err = cursor.Decode(sd)
		if err != nil {
			return nil, err
		}
		data = append(data, sd)
	}
	return data, nil

}
